package output.store;

import java.io.*;

import simulation.Statics;
import base.Particle;

public class ScopeStoreData
{
	//record time step
	private double deltaT = 0.02;
	//last recorded time step
	private double lastFrame = 0;
	//save how many steps in a single file
	private int fileSize = 10;
	//steps already stored in the file
	private int frameCount = 0;
	//saved file count
	private int savedCount = 0;
	
	StringBuffer file = new StringBuffer();
	
	public void refresh()
	{
		if(Statics.simulationTime > lastFrame + deltaT)
		{
			storeData();
			lastFrame += deltaT;
		}
	}
	
	private void storeData()
	{
		System.out.println("store t = " + String.format("%.6f", Statics.simulationTime));
		frameCount++;
		Particle[] particles = Statics.particleArray.particles;
		file.append(Statics.simulationTime + "\n");
		StringBuffer a = new StringBuffer();
		StringBuffer b = new StringBuffer();
		StringBuffer c = new StringBuffer();
		StringBuffer d = new StringBuffer();
		StringBuffer e = new StringBuffer();
		StringBuffer f = new StringBuffer();
		StringBuffer g = new StringBuffer();
		StringBuffer[] phase = new StringBuffer[particles[0].phaseCount];
		for(int j = 0; j < particles[0].phaseCount; j++)
		{
			phase[j] = new StringBuffer();
		}
		for(int i = 0; i < Statics.particleArray.particleCount; i++)
		{
			a.append(i + ", ");
			b.append(particles[i].pos[0] + ", ");
			c.append(particles[i].pos[1] + ", ");
			d.append(particles[i].pos[2] + ", ");
			
			e.append(particles[i].spd[0] + ", ");
			f.append(particles[i].spd[1] + ", ");
			g.append(particles[i].spd[2] + ", ");
			
			for(int j = 0; j < particles[0].phaseCount; j++)
			{
				phase[j].append(particles[i].phaseVolume[j] + ", ");
			}
		}
		file.append(a);
		file.append("\n");
		file.append(b);
		file.append("\n");
		file.append(c);
		file.append("\n");
		file.append(d);
		file.append("\n");
		file.append(e);
		file.append("\n");
		file.append(f);
		file.append("\n");
		file.append(g);
		file.append("\n");
		for(int j = 0; j < particles[0].phaseCount; j++)
		{
			file.append(phase[j]);
			file.append("\n");
		}
		file.append("\n");
		
		if(frameCount >= fileSize)
		{
			saveFile();
			frameCount = 0;
		}
	}
	
	private void saveFile()
	{
		System.out.println("--> save file: piece" + savedCount + ".data");
		try
		{
			BufferedWriter bw = new BufferedWriter(new FileWriter("output/store/data/piece" + savedCount + ".data"));
			bw.write(file.toString());
			bw.close();
			file.setLength(0);
			savedCount++;
		}
		catch(Exception e)
		{
			System.out.println("store data failed!");
		}
	}
}